package com.guchenbo.erp.inventory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guchenbo.erp.inventory.dto.InboundRequest;
import com.guchenbo.erp.inventory.dto.OutboundRequest;
import com.guchenbo.erp.inventory.entity.Inventory;
import com.guchenbo.erp.inventory.mapper.InventoryMapper;
import com.guchenbo.erp.inventory.service.InventoryCostService;
import com.guchenbo.erp.inventory.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 库存表 服务实现类
 * </p>
 *
 * @author guchenbo
 * @since 2025-07-12
 */
@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService {

    @Autowired
    private InventoryCostService inventoryCostService;

    @Override
    public void inbound(InboundRequest request) {
        Inventory inv = findOrCreate(request);
        // 修改库存
        inv.setQuantity(inv.getQuantity().add(request.getQuantity()));
        inv.setAvailableQty(inv.getAvailableQty().add(request.getQuantity()));
        this.updateById(inv);
//
//        logRepo.save(new InventoryCostLog(req.getProductId(), req.getWarehouseId(), "入库", req.getQuantity(), newTotal,
//                        req.getUnitPrice(), req.getRefOrderType(), req.getRefOrderId()));
    }

    private Inventory findOrCreate(InboundRequest request) {
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Inventory::getProductId, request.getProductId())
                        .eq(Inventory::getWarehouseId, request.getWarehouseId());
        Inventory inv = this.getOne(queryWrapper);
        if (inv == null) {
            inv = new Inventory();
            inv.setProductId(request.getProductId());
            inv.setWarehouseId(request.getWarehouseId());
            this.save(inv);
        }
        return inv;
    }

    @Override
    public void outbound(OutboundRequest request) {

    }
}
